package leo.peersim.common;

import java.io.File;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import peersim.config.Configuration;
import peersim.core.Linkable;
import peersim.core.Network;
import peersim.core.Node;
import peersim.dynamics.WireGraph;
import peersim.graph.Graph;

/**
 * 
 * @author leo
 * @version June 19, 2009
 */
public class GroupBuilder extends WireGraph {
	
	private Logger logger = Logger.getLogger(GroupBuilder.class.getName());
	
	private final int protocolID;
	
	public GroupBuilder(String prefix) {
		super(prefix);
		
		protocolID = Configuration.getPid(prefix + "." + "protocol");
		String log4jcfg = Configuration.getString(prefix + "." + "log4jcfg");
		PropertyConfigurator.configure((new File(new File("cfg"), log4jcfg)).getAbsolutePath());
	}

	@Override
	public void wire(Graph arg0) {
		
		logger.debug("Initializing memberships group for " + Network.size() + " nodes...");
		
		for (int i=0; i<Network.size(); i++) {
			Node node = Network.get(i);
			Linkable linkable = (Linkable) node.getProtocol(this.protocolID);
			
			for (int j=0; j<Network.size(); j++) {
				
				Node neighbour = Network.get(j);
				
				if (j==i) {
					continue;
				}
				
				linkable.addNeighbor(neighbour);
				logger.trace("Adding neighbour " + j + " to node " + i);
				
			}
		}
	}
}
